/*
 * Copyright (c) 2009, Takashi Ito
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the authors nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "tssp_internal.h"
#include "tssp_dvb_dr_66.h"


int tssp_dr_data_broadcast_id_parse(struct tssp_dr_data_broadcast_id *dest,
                                    const struct tssp_descriptor *src)
{
    int i;
    uint8_t *data;

    TSSP_ASSERT(dest);
    TSSP_ASSERT(src);

    if (src->tag != 0x66)
        return TSSP_STATUS_FAILED;

    if (src->length < 2)
        return TSSP_STATUS_FAILED;

    dest->id = (src->data[0] << 8) + src->data[1];
    data = &src->data[2];

    if (dest->id == 0x00F0 || dest->id == 0x00F1) {
        if (src->length % 2)
            return TSSP_STATUS_FAILED;
        dest->data.application.count = (src->length - 2) / 2;
        for (i = 0; i < dest->data.application.count; i++) {
            dest->data.application.type[i] =
                ((0x7F & data[i]) << 8) + data[i + 1];
        }
    } else {
        dest->data.specific.length = src->length - 2;
        memcpy(dest->data.specific.data, data, dest->data.specific.length);
    }

    return TSSP_STATUS_OK;
}

struct tssp_dr_data_broadcast_id *
tssp_dr_data_broadcast_id_create(const struct tssp_descriptor *src)
{
    struct tssp_dr_data_broadcast_id *dest;

    dest = malloc(sizeof(*dest));
    if (dest == NULL)
        return NULL;

    if (tssp_dr_data_broadcast_id_parse(dest, src) == TSSP_STATUS_OK)
        return dest;

    free(dest);
    return NULL;
}

